<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动排程监控系统</title>
    <script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            min-height: 100vh;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        h1 {
            color: white;
            text-align: center;
            margin-bottom: 30px;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .status-bar {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .status-item {
            display: inline-block;
            margin-right: 30px;
            padding: 10px 20px;
            border-radius: 5px;
            font-weight: bold;
        }

        .status-connected {
            background: #10b981;
            color: white;
        }

        .status-disconnected {
            background: #ef4444;
            color: white;
        }

        .status-info {
            background: #3b82f6;
            color: white;
        }

        .grid-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .panel {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .panel h2 {
            color: #667eea;
            margin-bottom: 15px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .log-container {
            background: #f8fafc;
            border-radius: 5px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }

        .log-entry {
            padding: 8px;
            margin-bottom: 8px;
            border-radius: 4px;
            border-left: 4px solid #667eea;
            background: white;
        }

        .log-success {
            border-left-color: #10b981;
            background: #f0fdf4;
        }

        .log-warning {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }

        .log-error {
            border-left-color: #ef4444;
            background: #fef2f2;
        }

        .log-time {
            color: #6b7280;
            font-size: 12px;
        }

        .schedule-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #667eea;
        }

        .schedule-card h3 {
            color: #1f2937;
            margin-bottom: 10px;
        }

        .schedule-detail {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            font-size: 14px;
        }

        .detail-item {
            padding: 5px;
        }

        .detail-label {
            color: #6b7280;
            font-weight: bold;
        }

        .detail-value {
            color: #1f2937;
        }

        .equipment-list {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 5px;
        }

        .equipment-tag {
            background: #667eea;
            color: white;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 12px;
        }

        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background 0.3s;
        }

        button:hover {
            background: #5568d3;
        }

        button:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .stat-number {
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.9em;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 自动排程监控系统</h1>

        <div class="status-bar">
            <span id="connectionStatus" class="status-item status-disconnected">未连接</span>
            <span id="lastUpdate" class="status-item status-info">最后更新: --</span>
            <button id="connectBtn" onclick="toggleConnection()">连接服务器</button>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number" id="totalScheduled">0</div>
                <div class="stat-label">已排程订单</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="totalSchedules">0</div>
                <div class="stat-label">生产计划数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="equipmentUpdates">0</div>
                <div class="stat-label">设备状态更新</div>
            </div>
        </div>

        <div class="grid-container">
            <div class="panel">
                <h2>📋 最新排程结果</h2>
                <div id="scheduleList" class="log-container">
                    <p style="color: #6b7280;">等待排程数据...</p>
                </div>
            </div>

            <div class="panel">
                <h2>📊 系统日志</h2>
                <div id="logContainer" class="log-container">
                    <p style="color: #6b7280;">等待日志消息...</p>
                </div>
            </div>
        </div>

        <div class="panel">
            <h2>⚙️ 设备状态更新</h2>
            <div id="equipmentLog" class="log-container">
                <p style="color: #6b7280;">等待设备状态更新...</p>
            </div>
        </div>
    </div>

    <script>
        let connection = null;
        let isConnected = false;
        let totalScheduledOrders = 0;
        let totalSchedulesCreated = 0;
        let equipmentUpdateCount = 0;

        async function toggleConnection() {
            if (isConnected) {
                await disconnect();
            } else {
                await connect();
            }
        }

        async function connect() {
            const connectBtn = document.getElementById('connectBtn');
            connectBtn.disabled = true;
            connectBtn.textContent = '连接中...';

            try {
                connection = new signalR.HubConnectionBuilder()
                    .withUrl("/equipmentStatusHub")
                    .withAutomaticReconnect()
                    .build();

                // 监听自动排程完成
                connection.on("ReceiveAutoSchedulingComplete", (data) => {
                    console.log("自动排程完成:", data);
                    totalScheduledOrders += data.ScheduledOrderCount;
                    totalSchedulesCreated += data.CreatedScheduleCount;
                    updateStats();
                    
                    addLog(data.Message, 'success', data.Time);
                    displayScheduleDetails(data.Details, data.Time);
                });

                // 监听自动排程警告
                connection.on("ReceiveAutoSchedulingWarning", (data) => {
                    console.log("自动排程警告:", data);
                    addLog(data.Message, 'warning', data.Time);
                });

                // 监听自动排程错误
                connection.on("ReceiveAutoSchedulingError", (data) => {
                    console.log("自动排程错误:", data);
                    addLog(data.Message, 'error', data.Time);
                });

                // 监听设备状态更新
                connection.on("ReceiveEquipmentStatusUpdate", (data) => {
                    console.log("设备状态更新:", data);
                    equipmentUpdateCount++;
                    updateStats();
                    addEquipmentLog(data);
                });

                // 监听生产计划更新
                connection.on("ReceiveProductionScheduleUpdate", (data) => {
                    console.log("生产计划更新:", data);
                    addLog(`生产计划已更新，共 ${data.TotalCount} 条记录`, 'success', data.Time);
                });

                // 监听订单创建
                connection.on("ReceiveAutoOrderCreated", (data) => {
                    console.log("自动创建订单:", data);
                    addLog(data.Message, 'success', data.Time);
                });

                await connection.start();
                isConnected = true;
                updateConnectionStatus(true);
                addLog("已连接到服务器", 'success');
                
            } catch (err) {
                console.error("连接失败:", err);
                addLog(`连接失败: ${err.message}`, 'error');
                updateConnectionStatus(false);
            }

            connectBtn.disabled = false;
            connectBtn.textContent = isConnected ? '断开连接' : '连接服务器';
        }

        async function disconnect() {
            if (connection) {
                await connection.stop();
                isConnected = false;
                updateConnectionStatus(false);
                addLog("已断开连接", 'warning');
                document.getElementById('connectBtn').textContent = '连接服务器';
            }
        }

        function updateConnectionStatus(connected) {
            const statusElement = document.getElementById('connectionStatus');
            if (connected) {
                statusElement.textContent = '已连接';
                statusElement.className = 'status-item status-connected';
            } else {
                statusElement.textContent = '未连接';
                statusElement.className = 'status-item status-disconnected';
            }
        }

        function updateStats() {
            document.getElementById('totalScheduled').textContent = totalScheduledOrders;
            document.getElementById('totalSchedules').textContent = totalSchedulesCreated;
            document.getElementById('equipmentUpdates').textContent = equipmentUpdateCount;
        }

        function addLog(message, type = 'info', time = null) {
            const logContainer = document.getElementById('logContainer');
            const timeStr = time ? new Date(time).toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN');
            
            if (logContainer.querySelector('p')) {
                logContainer.innerHTML = '';
            }

            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `
                <div class="log-time">${timeStr}</div>
                <div>${message}</div>
            `;
            
            logContainer.insertBefore(logEntry, logContainer.firstChild);
            
            // 保持最多50条日志
            while (logContainer.children.length > 50) {
                logContainer.removeChild(logContainer.lastChild);
            }

            updateLastUpdate(timeStr);
        }

        function displayScheduleDetails(details, time) {
            const scheduleList = document.getElementById('scheduleList');
            
            if (scheduleList.querySelector('p')) {
                scheduleList.innerHTML = '';
            }

            details.forEach(detail => {
                const card = document.createElement('div');
                card.className = 'schedule-card';
                card.innerHTML = `
                    <h3>订单 #${detail.OrderId}</h3>
                    <div class="schedule-detail">
                        <div class="detail-item">
                            <span class="detail-label">产品:</span>
                            <span class="detail-value">${detail.Goodsname}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">数量:</span>
                            <span class="detail-value">${detail.Number}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">工序数:</span>
                            <span class="detail-value">${detail.ProcessCount}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">开始时间:</span>
                            <span class="detail-value">${new Date(detail.StartTime).toLocaleString('zh-CN')}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">结束时间:</span>
                            <span class="detail-value">${new Date(detail.EndTime).toLocaleString('zh-CN')}</span>
                        </div>
                    </div>
                    <div style="margin-top: 10px;">
                        <span class="detail-label">使用设备:</span>
                        <div class="equipment-list">
                            ${detail.Equipments.map(eq => `<span class="equipment-tag">${eq}</span>`).join('')}
                        </div>
                    </div>
                `;
                
                scheduleList.insertBefore(card, scheduleList.firstChild);
            });

            // 保持最多10个排程卡片
            while (scheduleList.children.length > 10) {
                scheduleList.removeChild(scheduleList.lastChild);
            }
        }

        function addEquipmentLog(data) {
            const equipmentLog = document.getElementById('equipmentLog');
            
            if (equipmentLog.querySelector('p')) {
                equipmentLog.innerHTML = '';
            }

            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry log-success';
            logEntry.innerHTML = `
                <div class="log-time">${new Date(data.Time).toLocaleString('zh-CN')}</div>
                <div><strong>[${data.Source}]</strong> ${data.Message}</div>
                <div class="equipment-list" style="margin-top: 5px;">
                    ${data.Equipments.map(eq => `<span class="equipment-tag">${eq}</span>`).join('')}
                </div>
            `;
            
            equipmentLog.insertBefore(logEntry, equipmentLog.firstChild);
            
            // 保持最多20条设备日志
            while (equipmentLog.children.length > 20) {
                equipmentLog.removeChild(equipmentLog.lastChild);
            }
        }

        function updateLastUpdate(time) {
            document.getElementById('lastUpdate').textContent = `最后更新: ${time}`;
        }

        // 页面加载时自动连接
        window.addEventListener('load', () => {
            connect();
        });
    </script>
</body>
</html>
